package com.szt.mobile.inventory.modules.inventory.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.TypeReference;
import com.szt.mobile.inventory.R;
import com.szt.mobile.inventory.common.biz.CustomAsynTask;
import com.szt.mobile.inventory.common.entity.Assets;
import com.szt.mobile.inventory.common.entity.AssetsBean;
import com.szt.mobile.inventory.common.entity.AssetsDao;
import com.szt.mobile.inventory.common.entity.AssetsList;
import com.szt.mobile.inventory.common.entity.AssetsListDao;
import com.szt.mobile.inventory.common.entity.Commit;
import com.szt.mobile.inventory.common.entity.DaoMaster;
import com.szt.mobile.inventory.common.entity.DaoSession;
import com.szt.mobile.inventory.common.entity.Inventory;
import com.szt.mobile.inventory.common.entity.InventoryBean;
import com.szt.mobile.inventory.common.entity.InventoryDao;
import com.szt.mobile.inventory.common.entity.RequestEntity;
import com.szt.mobile.inventory.common.entity.ResponseEntity;
import com.szt.mobile.inventory.common.entity.User;
import com.szt.mobile.inventory.common.ui.BaseActivity;
import com.szt.mobile.inventory.common.ui.GeneralAdapter;
import com.szt.mobile.inventory.common.utils.CacheUtil;
import com.szt.mobile.inventory.common.utils.DBUtil;
import com.szt.mobile.inventory.common.utils.FastJsonUtils;
import com.szt.mobile.inventory.common.utils.GsonUtil;
import com.szt.mobile.inventory.common.utils.Network;
import com.szt.mobile.inventory.common.utils.Xutils;
import com.szt.mobile.inventory.modules.inventory.biz.InventoryBiz;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by yanzhaodi on 2017/11/16.
 */

@SuppressWarnings("unchecked")
public class InventoryActivity extends BaseActivity {

    private static final String TAG = "InventoryActivity";

    @BindView(R.id.tv_inventory_start_time)
    TextView startTimeTv;

    @BindView(R.id.tv_inventory_end_time)
    TextView endTimeTv;

    @BindView(R.id.cb_inventory_choose_all)
    CheckBox chooseAllCb;

    @BindView(R.id.lv_inventory)
    ListView inventoryLv;

    private String startTime;
    private String endTime;
    private AssetsBean mAssetsBean;
    List<Assets> mAssets;
    private InventoryAdapter inventoryAdapter;

    private InventoryDao inventoryDao;
    private AssetsListDao assetsListDao;
    private AssetsDao assetsDao;
    private Commit mCommit;

    public static final String KEY_INVENTORY = "key_inventory";

    private static final int REQUEST_CODE_INVENTORY = 1;
    private Xutils mXutils;
    private InventoryBean mInventoryBean;
    private List<Inventory> inventories;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_inventory);

        inventoryDao = DBUtil.getInventoryDao(getApplicationContext());
        assetsListDao = DBUtil.getAssetsListDao(getApplicationContext());
        assetsDao = DBUtil.getAssetsDao(getApplicationContext());

        mXutils = Xutils.getInstance();

        ButterKnife.bind(this);
        initTime();

        loadDataFromDB();

        chooseAllCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                inventoryAdapter.isChooseAll(isChecked);
            }
        });
    }

    private void initTime() {
        SimpleDateFormat sf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        sf.applyPattern("yyyy-MM-dd");

        Date now = new Date();
        endTime = sf.format(now);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_MONTH, -7);

        startTime = sf.format(calendar.getTime());

        startTimeTv.setText(startTime);
        endTimeTv.setText(endTime);
    }

    @OnClick(R.id.tv_inventory_start_time)
    public void chooseStartTime(View view) {
        ChooseDateDialog startTimeDialog = new ChooseDateDialog(this, startTime);
        startTimeDialog.setDateCallback(new ChooseDateDialog.DateCallback() {
            @Override
            public void onChoose(String date) {
                startTime = date;
                startTimeTv.setText(startTime);
            }
        });
        startTimeDialog.show();
    }

    @OnClick(R.id.tv_inventory_end_time)
    public void chooseEndTime(View view) {
        ChooseDateDialog endTimeDialog = new ChooseDateDialog(this, endTime);
        endTimeDialog.setDateCallback(new ChooseDateDialog.DateCallback() {
            @Override
            public void onChoose(String date) {
                endTime = date;
                endTimeTv.setText(endTime);
            }
        });
        endTimeDialog.show();
    }

    public void exit(View view) {
        finish();
    }

    private void loadDataFromDB() {
        final List<Inventory> inventories = inventoryDao.loadAll();
//        if (Network.isOpenNetwork(InventoryActivity.this)) {
//            sync(startTimeTv);
//        } else {
        for (Inventory inventory : inventories) {
            List<AssetsList> assetsLists = assetsListDao._queryInventory_Detail(inventory.getId_());
            for (AssetsList assetsList : assetsLists) {
                assetsList.asset = assetsDao._queryAssetsList_Asset(assetsList.get_id());
                inventory.detail = assetsLists;
            }
//            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    initListView(inventories);
                }
            });
        }
    }

    public void sync(View view) {
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime) && startTime.compareTo(endTime) > 0) {
            Toast.makeText(this, "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (Network.isOpenNetwork(InventoryActivity.this) == true) {


            try{
                showLoading();
                InventoryBiz.getInventoryList(startTime, endTime, mXutils, new Xutils.XCallBack() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("inventory", "下载盘点单返回报文:" + result);
                        mInventoryBean = FastJsonUtils.getJsonToBean(result, InventoryBean.class);
                        inventories = mInventoryBean.getData();
                        if (inventories != null) {
                            initListView(inventories);
                            Observable.fromCallable(new Callable<Boolean>() {
                                @Override
                                public Boolean call() {
                                    updateDB(inventories);
                                    getInventoryAssets(inventories);
                                    return true;
                                }
                            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Action1<Boolean>() {
                                        @Override
                                        public void call(Boolean aBoolean) {
                                            hideLoading();
                                        }
                                    });
                        } else {
                            showToast("请求失败");
                            hideLoading();
                        }
                    }

                    @Override
                    public void onError(String e) {
                        hideLoading();
                        showToast(e);

                    }
                });
            }catch (Exception e){
                inventoryDao.deleteAll();
                assetsListDao.deleteAll();
                assetsDao.deleteAll();
                showToast("盘点错误, 已清除本地表, 请重新同步");
            }

        } else {
            showToast("网络连接失败");
        }
    }

    private void getInventoryAssets(List<Inventory> inventories) {
        for (final Inventory inventory : inventories) {
            List<String> autoIds = new ArrayList<>();
            final List<Assets> ass = new ArrayList<>();
            for (AssetsList assetsList : inventory.detail) {
                for (Assets assets : assetsList.asset) {
                    assets.setAssetsListId(assetsList.get_id());
                    autoIds.add(assets.get_id() + "");
                    ass.add(assets);
                }
            }

            if (autoIds.isEmpty()) {
                continue;
            }
            InventoryBiz.getAssets(autoIds, mXutils, new Xutils.XCallBack() {
                @Override
                public void onResponse(String result) {
                    mAssetsBean = GsonUtil.GsonToBean(result, AssetsBean.class);
                    mAssets = mAssetsBean.getData();

                }

                @Override
                public void onError(String e) {
                    hideLoading();

                }

            });

            if (null == mAssets) {
                continue;
            }
            for (Assets as : mAssets) {
                for (Assets a : ass) {
                    if (a.ASSET_ID.equals(as.aUTOID)) {
                        as.set_id(a.get_id());
                        as.setAssetsListId(a.getAssetsListId());
                        as.RESULT_TYPE = a.RESULT_TYPE;
                        break;
                    }
                }
            }
            assetsDao.updateInTx(mAssets);
            loadDataFromDB();
        }

    }

    DaoSession mDaoSession;
    private void updateDB(final List<Inventory> inventories) {
        mDaoSession= DaoMaster.newDevSession(InventoryActivity.this, CacheUtil.getCacheUserName());
        mDaoSession.startAsyncSession().runInTx(new Runnable() {
            @Override
            public void run() {
                inventoryDao.deleteAll();
                inventoryDao.insertOrReplaceInTx(inventories);
                inventoryDao.detachAll();

                for (Inventory inventory : inventories) {
                    List<AssetsList> assetsLists = inventory.getDetail();
                    if (assetsLists == null) {
                        continue;
                    }
                    for (final AssetsList assetsList : assetsLists) {
                        assetsList.setInventoryId(inventory.getId_());
                        assetsListDao.insertOrReplaceInTx(assetsList);
                        assetsListDao.detachAll();
                        for (final Assets assets : assetsList.asset) {
                            assets.setAssetsListId(assetsList.get_id());
                            assetsDao.insertOrReplaceInTx(assets);
                            assetsDao.detachAll();
                        }
                    }
                }
            }
        });
    }

    private void initListView(List<Inventory> inventories) {
        if (inventoryAdapter == null) {
            inventoryAdapter = new InventoryAdapter(this, inventories);
            inventoryLv.setAdapter(inventoryAdapter);
        } else {
            inventoryAdapter.setData(inventories);
        }

        inventoryLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Inventory inventory = inventoryAdapter.getItem(position);

                List<Assets> assets = new ArrayList<>();
                if (null != inventory.detail) {
                    for (AssetsList assetsList : inventory.detail) {
                        assets.addAll(assetsList.asset);
                    }
                }

                if (assets.isEmpty()) {
                    showToast("此单据内盘点设备为空，不能盘点，请核实单据！");
                    return;
                }

                Intent intent = new Intent(getApplicationContext(), InventoryListActivity.class);
                intent.putExtra(KEY_INVENTORY, inventory);
                startActivityForResult(intent, REQUEST_CODE_INVENTORY);
                inventory.setStatus(-1);
                inventoryDao.update(inventory);
                inventoryAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_INVENTORY && resultCode == RESULT_OK) {
            loadDataFromDB();
            return;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public void commit(View view) {
        if (Network.isOpenNetwork(InventoryActivity.this)==true){

            final List<Inventory> inventories = inventoryAdapter.getChooseItem();
            if (inventories.isEmpty()) {
                inventories.addAll(inventoryAdapter.getData());
            }

            final List<Inventory> finishedInventories = new ArrayList<>();
            for (Inventory inventory : inventories) {
                if (inventory.getStatus() == 2) {
                    finishedInventories.add(inventory);
                }
            }

            if (finishedInventories.isEmpty()) {
                showToast("没有已完成的盘点单,无法提交！");
                return;
            }

            showLoading();
            InventoryBiz.uploadInventory(finishedInventories, mXutils, new Xutils.XCallBack() {
                @Override
                public void onResponse(String result) {
                    Log.e("InventoryActivity", "上传盘点单返回报文:" + result);
                    hideLoading();
                    mCommit = GsonUtil.GsonToBean(result, Commit.class);
                    if (mCommit.getData().getResultCode() == 1) {
                        inventoryAdapter.isChooseAll(false);
                        inventoryAdapter.getData().removeAll(finishedInventories);
                        inventoryDao.deleteInTx(finishedInventories);
                        for (Inventory in : finishedInventories) {
                            List<AssetsList> assetsLists = assetsListDao.queryRaw("where T.'INVENTORY_ID' = ?", String.valueOf(in.getId_()));
                            for (AssetsList a1 : assetsLists) {
                                assetsDao.deleteInTx(assetsDao.queryRaw("where T.'ASSETS_LIST_ID' = ?", String.valueOf(a1.get_id())));
                            }
                            assetsListDao.deleteInTx(assetsLists);
                        }
                        inventoryAdapter.notifyDataSetChanged();
                    } else {
                        showToast("请求失败");
                    }

                }

                @Override
                public void onError(String e) {
                    hideLoading();
                    showToast(e);

                }
            });
        }else {
            showToast("网络连接失败");
        }
    }

    private static class InventoryAdapter extends GeneralAdapter<Inventory> {
        public InventoryAdapter(Context ctx, List<Inventory> data) {
            super(ctx, R.layout.view_inventory_item, data);
        }

        private List<Integer> chooseIds = new ArrayList<>();

        public void isChooseAll(boolean isChooseAll) {
            chooseIds.clear();

            if (isChooseAll) {
                for (int i = 0; i < getCount(); i++) {
                    chooseIds.add(i);
                }
            }

            notifyDataSetChanged();
        }

        @Override
        public void convert(ViewHolder holder, Inventory item, final int position) {
            final CheckBox chooseCb = holder.getView(R.id.cb_inventory_item_choose);
            TextView indexTv = holder.getView(R.id.tv_inventory_item_index);
            TextView addressTv = holder.getView(R.id.tv_inventory_item_address);
            TextView descTv = holder.getView(R.id.tv_inventory_item_desc);
            TextView timeTv = holder.getView(R.id.tv_inventory_item_time);
            Button statusTv = holder.getView(R.id.tv_inventory_item_operation);

            indexTv.setText(String.valueOf(position + 1));
            addressTv.setText(item.sDESCRIBE);
            descTv.setText(item.sDESCRIBE);

            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            timeTv.setText(sf.format(item.make_date));

            chooseCb.setChecked(chooseIds.contains(position));

            chooseCb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (chooseCb.isChecked()) {
                        chooseIds.add(position);
                    } else {
                        chooseIds.remove(Integer.valueOf(position));
                    }
                }
            });
            if (item.getStatus() != 2) {
                statusTv.setText("点击\n盘点");
            } else {
                statusTv.setText("盘点\n完成");
            }

        }

        public List<Inventory> getChooseItem() {
            List<Inventory> inventories = new ArrayList<>();
            for (Integer i : chooseIds) {
                inventories.add(getItem(i));
            }

            return inventories;
        }
    }
}
